﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

using ECCIT;
using ECCIT.Data;
using OgilvyOne.Sharan.Model;
using OgilvyOne.Sharan.IDAL;

namespace OgilvyOne.Sharan.DAL
{
    public class WeiboRelationDAL : IDALWeiboRelation
    {
        private const string C_TABLE_NAME = "tbl_WeiboRelation";
        private const string col_UserWeiboID = "col_WeiboUserID";
        private const string col_FriendWeiboUserID = "col_FriendWeiboUserID";

        private const string C_SQL_SELECT_ALL_FRIENDS = "select " + col_UserWeiboID + "," + col_FriendWeiboUserID + " from " + C_TABLE_NAME + " where " + col_UserWeiboID + "={0}";

        #region IDALWeiboRelation 成员

        public List<long?> GetFriendWeiboUserIDs(long? weiboUserID)
        {
            try
            {
                List<long?> ids = new List<long?>();
                string cmd = string.Format(C_SQL_SELECT_ALL_FRIENDS, weiboUserID);
                using (IDataReader reader = DBHelper.ExecuteReader(cmd))
                {
                    while (reader.Read())
                    {
                        long? id = (long?)reader[col_FriendWeiboUserID];

                        ids.Add(id);
                    }
                }

                return ids;
            }
            catch (Exception ex)
            {
                throw new Exception("Error occurred in WeiboRelationDAL.GetFriendWeiboUserIDs(). Message: " + ex.Message);
            }
        }

        public ResultInfo Save(long? weiboUserID, List<long?> friendWeiboUserIDs)
        {
            ResultInfo result = new ResultInfo(false);

            // 保存的逻辑很简单，就是先删除，然后新增
            try
            {
                string delCmd = "delete from " + C_TABLE_NAME + " where " + col_UserWeiboID + "=" + weiboUserID.Value;
                HttpContext.Current.Session["del"] = delCmd;
                DBHelper.ExecuteNonQuery(delCmd);

                int i = 0;
                foreach (long? friendID in friendWeiboUserIDs)
                {
                    string insCmd = "insert into " + C_TABLE_NAME + " (" + col_UserWeiboID + "," + col_FriendWeiboUserID + ") values (" + weiboUserID.Value + "," + friendID.Value + ")";
                    HttpContext.Current.Session["ins" + i] = insCmd;
                    DBHelper.ExecuteNonQuery(insCmd);
                    i++;
                }

                result.Result = true;
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = ex.Message;
            }

            return result;
        }

        #endregion
    }
}